<template>
	<div class="echart"></div>
</template>
  
<script>
import * as echarts from 'echarts';
export default {
	name: 'Echart',
	components: {
	},
	props: {
		dataSource: {
			default: null
		}
	},
	data() {
		return {
			title: "",
			subTitle: "",
			seriesName: "",
			pieData: [],
			myChart: null,
			timer: null,
		};
	},
	watch: {
		dataSource: {
			// 监听 props.dataSource 的变化
			handler(newVal, _) {
				this.handleDataSource(newVal);
			},
			deep: true,
			immediate: true,
		}
	},
	created() {
	},
	mounted() {
		window.addEventListener('resize', this.resizeChart);
	},
	beforeUnmount() {
		window.removeEventListener('resize', this.resizeChart);
	},
	methods: {
		handleDataSource(obj) {
			if (!obj) { return; }
			// console.log("当前组件接收数据源为：", obj);

			this.title = obj.title || "";
			this.subTitle = obj.subTitle || "";
			this.seriesName = obj.seriesName || "";
			this.pieData = obj.pieData || [];

			this.$nextTick(() => {
				// console.log("当前组件 id 为：", this.$el.id);
				this.initChart();
				this.resizeChart();
			})
		},

		// 获取 series 数据
		getSeries(pieData) {
			return [{
				name: this.seriesName,
				type: 'pie',
				radius: '50%',
				data: pieData || [],
				emphasis: {
					itemStyle: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)'
					}
				}
			}];
		},

		// 获取 echart 配置项
		getOption() {
			return {
				title: {
					text: this.title,
					subtext: this.subTitle || '',
					left: 'center'
				},
				tooltip: {
					trigger: 'item'
				},
				legend: {
					orient: 'vertical',
					left: 'left'
				},
				series: this.getSeries(this.pieData)
			};
		},

		// 初始化 echart 图表
		initChart() {
			var chartDom = document.getElementById(this.$el.id);
			if (!chartDom) {
				return;
			}
			echarts.dispose(chartDom);
			
			var myChart = echarts.init(chartDom);
			var option = this.getOption();
			option && myChart.setOption(option);
			this.myChart = myChart;
		},

		// 重置 echart 尺寸
		resizeChart() {
			setTimeout(() => {
				clearTimeout(this.timer);
				this.timer = setTimeout(() => {
					if (this.myChart) {
						// console.log("resize:", this.$el.id);
						this.myChart.resize();
					}
				}, 200);
			})
		}
	}
};
</script>
  
<style scoped lang="scss">
.echart {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
	background-color: #fff;
}
</style>